<?php

namespace App\Jobs;

use App\Models\User;
use App\Models\GoldProduct;
use App\Services\SettleGoldRecordReselling\SettleGoldRecordReselling;
use Illuminate\Bus\Queueable;
use App\Events\GoldRecordPaidEvent;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use App\Services\MakeGoldRecord\MakeGoldRecord;
use App\Services\ApplyGoldProductReselling\ApplyGoldProductReselling;

class RobotReclimJob implements ShouldQueue
{
	use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

	public User $robot;
	public GoldProduct $goldProduct;

	public function __construct(User $robot, GoldProduct $goldProduct)
	{
		$this->robot = $robot;
		$this->goldProduct = $goldProduct;
	}

	public function handle()
	{
        $user = $this->robot;

        if ($user->name != 'reclaimer') return;

		$p = $this->goldProduct;

		$pid = $p->id;
		$rid = $p->gold_round_id;

		if (! GoldProduct::sIsInSoldCache($pid, $rid)) {

			GoldProduct::sAddToSoldCache($pid, $rid);
            GoldProduct::sDelFromAliveCache($pid, $rid);

			$record = app(MakeGoldRecord::class, [
				'user' => $user,
				'unpaidCacheId' => $p
			])->make();

			if ($record) {
				event(new GoldRecordPaidEvent($record));
                app(SettleGoldRecordReselling::class, ['record' => $record])->run();
				app(ApplyGoldProductReselling::class, [
					'user' => $user,
					'pendingCacheId' => $record
				])->apply();
			}
		}
	}
}
